package com.wenxin.demo.controller;

import com.alibaba.fastjson2.JSON;
import com.gearwenxin.client.ernie.ErnieBot4Client;
import com.wenxin.demo.aes.AesException;
import com.wenxin.demo.aes.WXBizJsonMsgCrypt;
import com.wenxin.demo.util.WecomUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/wecom")
public class WecomController {

    @Value("${wecom.token}")
    private String token;

    @Value("${wecom.encoding-aes-key}")
    private String encodingAesKey;

    @Value("${wecom.corp-id}")
    private String corpId;

    @Resource
    WecomUtil httpUtil;

    @Resource
    private ErnieBot4Client ernieBot4Client;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/getAccessToken")
    public String getAccessToken() throws Exception {
        return httpUtil.getAccessToken();
    }

    @GetMapping("/sendMsg")
    public void sendMsg(String msg) throws Exception {
        httpUtil.sendMsg("LinSen", msg);
    }

    @ResponseBody
    @RequestMapping("/verify")
    public void verify(@RequestParam("msg_signature") String msgSignature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam(value = "echostr", required = false) String echostr,
                       @RequestBody(required = false) Map<String, Object> param,
                       HttpServletResponse response)  {

        try {
            System.out.println("msgSignature: " + msgSignature);
            System.out.println("timestamp: " + timestamp);
            System.out.println("nonce: " + nonce);
            System.out.println("echostr: " + echostr);
            WXBizJsonMsgCrypt crypt = new WXBizJsonMsgCrypt(token, encodingAesKey, corpId);

            if (null != echostr) {
                // response直接返回result
                try {
                    String result = crypt.VerifyURL(msgSignature, timestamp, nonce, echostr);
                    System.out.println("result: " + result);
                    response.getWriter().write(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (null != param) {
                System.out.println("param: " + JSON.toJSONString(param));

                String toUserName = (String) param.get("ToUserName");
                String Encrypt = (String) param.get("Encrypt");
                String AgentID = (String) param.get("AgentID");

                String result = crypt.decrypt(Encrypt);
                System.out.println("result: " + result);

                // result为一个xml串，解析出其中Content标签的内容
                String fromUserName = DocumentHelper.parseText(result).getRootElement().element("FromUserName").getText();

                // result为一个xml串，解析出其中Content标签的内容
                String data = DocumentHelper.parseText(result).getRootElement().element("Content").getText();
                System.out.println("data: " + data);

                // httpUtil.sendMsg(fromUserName, "我已经收到你发给我的消息，消息内容: " + data);

                if (data.equals("newchat")) {
                    redisTemplate.delete("chat_his_" + fromUserName);
                    httpUtil.sendMsg(fromUserName, "开启新会话(3600秒过期)");
                } else {
                    String msgId = "msg_id_" + Math.random();
                    if (redisTemplate.hasKey("chat_his_" + fromUserName)) {
                        msgId = (String) redisTemplate.opsForValue().get("chat_his_" + fromUserName);
                        System.out.println("continue chat: " + msgId);
                    } else {
                        redisTemplate.opsForValue().set("chat_his_" + fromUserName, msgId, 3600, TimeUnit.SECONDS);
                        System.out.println("new chat: " + msgId);
                    }

                    ernieBot4Client.chatCont(data, msgId).subscribe(response1 -> {
                        try {
                            httpUtil.sendMsg(fromUserName, response1.getResult());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }




//                ernieBot4Client.chatSingle(data).subscribe(response1 -> {
//                    try {
//                        httpUtil.sendMsg(fromUserName, response1.getResult());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
